package util

import (
    "errors"
    "github.com/dgrijalva/jwt-go"
    "time"
    "yi-shou-backstage/config"
)

var Secret = []byte(config.Conf.Secret)

type MyClaims struct {
    UserId int `json:"user_id"`
    jwt.StandardClaims
}

// 生成token
func GenerateToken(user_id int) (string, error) {
    ExpireTime := time.Now().Add(24 * time.Hour).Unix()
    SetClaims := MyClaims{
        UserId: user_id,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: ExpireTime,
            Issuer: "yi-shou-pc",
        },
    }

    reqClaim := jwt.NewWithClaims(jwt.SigningMethodHS256, SetClaims)
    token, err := reqClaim.SignedString(Secret)
    return token, err
}

// 刷新token，有效期14天
func GenerateRefreshToken(user_id int) (string, error) {
    ExpireTime := time.Now().Add(14 * 24 * time.Hour).Unix()
    SetClaims := MyClaims{
        UserId: user_id,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: ExpireTime,
            Issuer: "yi-shou-pc",
        },
    }

    reqClaim := jwt.NewWithClaims(jwt.SigningMethodHS256, SetClaims)
    token, err := reqClaim.SignedString(Secret)
    return token, err
}

// 验证Token
func CheckToken(token string) (*MyClaims, error) {
    SetToken, _ := jwt.ParseWithClaims(token, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
        return Secret, nil
    })
    if key, _ := SetToken.Claims.(*MyClaims); SetToken.Valid {
        return key, nil
    }else  {
        return nil, errors.New("Token is invalid")
    }
}
